import React, {useState} from 'react';
import {Cascader} from "antd";
import {SizeType} from "antd/es/config-provider/SizeContext";

interface RegionCascaderProps {
  placeholder?: string
  options: any[],
  value?: any,
  onChange?: (value?: string) => void,
  size?: SizeType
  style?: any
  depth?: number
  fullPath?: boolean
  disabled?: boolean
}

/**
 * 行政区域下拉选择组件
 * @param options 区域树
 * @param value 值
 * @param onChange onChange事件
 * @param cascaderProps 其他级联选项配置
 * @constructor
 */
const RegionCascader: React.FC<RegionCascaderProps> = ({options, value, onChange, ...cascaderProps}) => {
    const [open, setOpen] = useState<boolean>(false);

    const parseValue = (options: any[], value: any, parentValues?: any[]) => {
      parentValues = parentValues || [];
      for (let i = 0; i < options.length; i++) {
        const item = options[i];
        const tempValues = [...parentValues, item.value]
        if (item.value === value) {
          return tempValues;
        } else if (item.children && item.children.length) {
          const result: any[] = parseValue(item.children, value, tempValues);
          if (result.length) {
            return result
          }
        }
      }
      return [];
    }

    const handleChange = (values: any[]) => {
      setOpen(false);
      const _value = (values && values.length) ? [...values].pop() : null;
      onChange && onChange(_value)
    }

    let cascaderValue = value;
    const parsedValue = parseValue(options || [], value);
    if (parsedValue && parsedValue.length) {
      cascaderValue = parsedValue;
    }
    return (
      <Cascader value={cascaderValue} placeholder={"请选择行政区划"} {...cascaderProps} options={options}
                changeOnSelect
                onBlur={() => setOpen(false)} expandTrigger={"hover"}
                onChange={handleChange} onClick={() => setOpen(!open)} open={open}/>
    );
  }
;

export default RegionCascader;
